<script lang="ts" setup>
import EZUIKit from "ezuikit-js";
import { onMounted, ref } from "vue";
import { getAccessToken } from "../apis/EZUIKIT";
import axios from "axios";

interface IPlayer {
  play: Function;
  stop: Function;
  getOSDTime: Function;
  capturePicture: Function;
  openSound: Function;
  closeSound: Function;
  startSave: Function;
  stopSave: Function;
  startTalk: Function;
  stopTalk: Function;
  fullScreen: Function;
  destroy: Function;
}

let player: IPlayer;

const play = () => {
  const playPromise = player.play();
  playPromise.then((data: any) => {
    console.log("promise 获取 数据", data);
  });
};

const stop = () => {
  const stopPromise = player.stop();
  stopPromise.then((data: any) => {
    console.log("promise 获取 数据", data);
  });
};

const getOSDTime = () => {
  const getOSDTimePromise = player.getOSDTime();
  getOSDTimePromise.then((data: any) => {
    console.log("promise 获取 数据", data);
  });
};

const capturePicture = () => {
  const capturePicturePromise = player.capturePicture(
    `${new Date().getTime()}`
  );
  capturePicturePromise.then((data: any) => {
    console.log("promise 获取 数据", data);
  });
};

const openSound = () => {
  const openSoundPromise = player.openSound();
  openSoundPromise.then((data: any) => {
    console.log("promise 获取 数据", data);
  });
};

const closeSound = () => {
  const openSoundPromise = player.closeSound();
  openSoundPromise.then((data: any) => {
    console.log("promise 获取 数据", data);
  });
};

const startSave = () => {
  const startSavePromise = player.startSave(`${new Date().getTime()}`);
  startSavePromise.then((data: any) => {
    console.log("promise 获取 数据", data);
  });
};

const stopSave = () => {
  const stopSavePromise = player.stopSave();
  stopSavePromise.then((data: any) => {
    console.log("promise 获取 数据", data);
  });
};

const ezopenStartTalk = () => {
  player.startTalk();
};

const ezopenStopTalk = () => {
  player.stopTalk();
};

const fullScreen = () => {
  player.fullScreen();
};

const destroy = () => {
  const destroyPromise = player.destroy();
  destroyPromise.then((data: any) => {
    console.log("promise 获取 数据", data);
  });
  player = null!;
};

const url = "https://open.ys7.com/api/lapp/token/get";
let accessToken = "";
const appKey = "64c62b1788d24353a098d161af219a36",
  secret = "118c36bdae0cd624488abb0ba1376b84";

const videoValue = ref(localStorage.getItem("video") || "2");

const handleCommand = (command) => {
  localStorage.setItem("video", command);
  videoValue.value = command;
  location.reload();
};

const fetchAccessToken = async () => {
  const params = new URLSearchParams();
  params.append('appKey', appKey);
  params.append('appSecret', secret);

  try {
    const response = await axios.post(url, params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    console.log("Response:", response.data.data.accessToken);
    return response.data.data.accessToken; // 返回 accessToken
  } catch (error) {
    console.error("Error:", error);
    throw error; // 抛出错误，方便外部捕获
  }
};

const init = async () => {
  try {
    const token = await fetchAccessToken(); // 等待 fetchAccessToken 完成并获取 accessToken
    if (player) {
      destroy();
    }
    console.group("mounted 组件挂载完毕状态===============》");
    player = new EZUIKit.EZUIKitPlayer({
      id: "video-container", // 视频容器ID
      accessToken: token, // 使用返回的 accessToken
      url: "ezopen://open.ys7.com/K92940713/" + videoValue.value + ".hd.live",
      template: "pcLive",
      plugin: ["talk"], // 加载插件，talk-对讲
      handleError: (err: any) => {
        console.error("handleError", err); // 检查是否有错误信息
      },
      staticPath: "/ezuikit_static", // 如果想使用本地静态资源，请复制根目录下ezuikit_static 到当前目录下， 然后设置该值
    });
    window.player = player;
  } catch (error) {
    console.error("初始化失败:", error);
  }
};

onMounted(() => {
  init();
});
</script>

<template>
  <div class="hello-ezuikit-js" style="width: 100%; height: 110%" @contextmenu="contextmenu">
    <div class="cd">
      <el-dropdown @command="handleCommand" class="xl" trigger="click" size="large">
        <span class="el-dropdown-link" style="padding: 0.1rem; border-radius: 10px">
          切换监控
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="2">一号棚</el-dropdown-item>
            <el-dropdown-item command="4">二号棚</el-dropdown-item>
            <el-dropdown-item command="6">三号棚</el-dropdown-item>
            <el-dropdown-item command="7">四号棚</el-dropdown-item>
            <el-dropdown-item command="9">五号棚</el-dropdown-item>
            <el-dropdown-item command="10">六号棚</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div v-if="videoValue != 10" id="video-container" style="width: 100%; height: 85%"></div>
    <div class="video" v-if="videoValue == 10">
      <div class="header">
        <span style="margin-right: .1875rem;margin-left: .125rem">K92940713</span>
        <span>天歌种鹅厂</span>
      </div>
      <video style="width: 100%;height: 100%;transform: scaleY(1.10);transform-origin: top;" muted autoplay loop>
        <source src="../assets/video/new.mp4" type="video/mp4">
      </video>
    </div>
  </div>
</template>

<style scoped>
.cd {
  position: relative;
  top: 0;
  left: 0;
}

.xl {
  text-align: center;
}

.video {
  .header {
    height: .4rem;
    width: 11rem;
    background-color: #000;

    span {
      line-height: .4rem;
    }
  }
}
</style>
